﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NHibernate;
using VegetableStore.Providers;
using VegetableStore.Util;
using System.IO;
using VegetableStore.Domains;

namespace VegetableStore.Controllers
{
    public class ImageController : Controller
    {
        private ISession nhibernateSession;

        public ImageController()
        {
            nhibernateSession = SessionProvider.Instance.GetSession();
        }

        [AllowAnonymous]
        [HttpPost]
        public JsonResult UploadImage(string token, HttpPostedFileBase file)
        {
            try
            {
                if (token == null) return Json(new { result = "FAILURE", msg = "token이 입력되어야 합니다." }, JsonRequestBehavior.AllowGet);
                if (!AuthUtil.IsAuthorized(token)) return Json(new { result = "FAILURE", msg = "인증되지 않은 접근입니다." }, JsonRequestBehavior.AllowGet);
                
                string imageRootPath = System.Configuration.ConfigurationManager.AppSettings["IMAGE_ROOT_PATH"].ToString();
                string imageRootUrl = System.Configuration.ConfigurationManager.AppSettings["IMAGE_ROOT_URL"].ToString();
                
                if (file.ContentLength > 0)
                {
                    string originalFileName = Path.GetFileName(file.FileName);
                    string newFileName = GenerateFileName(originalFileName);
                    var path = Path.Combine(imageRootPath, newFileName);
                    file.SaveAs(path);
                    string imageUrl = imageRootUrl + newFileName;

                    Image image = new Image
                    {
                        Name = newFileName,
                        Url = imageUrl
                    };
                    using (var tx = nhibernateSession.BeginTransaction())
                    {
                        try
                        {
                            nhibernateSession.Save(image);
                            nhibernateSession.Flush();
                            tx.Commit();
                        }
                        catch (Exception te)
                        {
                            tx.Rollback();
                            SessionProvider.Instance.CloseSession();
                            throw te;
                        }
                    }
                    return Json(new { result = "SUCCESS", data = image }, JsonRequestBehavior.AllowGet);
                }
                return Json(new { result = "FAILURE", msg = "이미지 업로드에 실패했습니다." }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception e)
            {
                if (e.InnerException == null) return Json(new { result = "FAILURE", msg = e.Message }, JsonRequestBehavior.AllowGet);
                else return Json(new { result = "FAILURE", msg = e.InnerException.Message }, JsonRequestBehavior.AllowGet);
            }
        }

        [AllowAnonymous]
        [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
        public JsonResult GetImage(string token, int? imageId)
        {
            try
            {
                if (token == null) return Json(new { result = "FAILURE", msg = "token이 입력되어야 합니다." }, JsonRequestBehavior.AllowGet);                
                if (imageId == null) return Json(new { result = "FAILURE", msg = "imageId가 입력되어야 합니다." }, JsonRequestBehavior.AllowGet);
                if (!AuthUtil.IsAuthorized(token)) return Json(new { result = "FAILURE", msg = "인증되지 않은 접근입니다." }, JsonRequestBehavior.AllowGet);
                
                Image image = nhibernateSession.Get<Image>(imageId);
                return Json(new { result = "SUCCESS", data = image }, JsonRequestBehavior.AllowGet);  
            }
            catch (Exception e)
            {
                if (e.InnerException == null) return Json(new { result = "FAILURE", msg = e.Message }, JsonRequestBehavior.AllowGet);
                else return Json(new { result = "FAILURE", msg = e.InnerException.Message }, JsonRequestBehavior.AllowGet);
            }
        }

        private string GenerateFileName(string fileName)
        {
            string pureFileName = Path.GetFileNameWithoutExtension(fileName);
            string extention = Path.GetExtension(fileName);
            return pureFileName + System.DateTime.Now.ToString("_yyMMddhhmmss") + extention;
        }
    }
}
